Skip to content

在 ASP.NET Core 實作 GDPR

TLDR

  • GDPR 要求網站必須告知使用者 Cookie 使用情況,並提供隱私權政策連結。
  • 實作核心在於區分「必要性 Cookies」與「非必要性 Cookies」。
  • ASP.NET Core 透過 CookiePolicyOptionsUseCookiePolicy 中介軟體管理同意狀態。
  • 若需嚴格控管,應將非必要 Cookie 設定為 IsEssential = false,並透過 ITrackingConsentFeature 檢查使用者是否已同意。
  • 建議在 Program.cs 中設定 CheckConsentNeeded 來決定是否強制要求使用者同意。

GDPR 規範與網站實作原則

GDPR (General Data Protection Regulation) 旨在規範歐盟個人的資料與隱私。在網頁開發中,這通常體現為「Cookie 同意橫幅 (Consent Banner)」。

實作常見做法

  • 隱私權政策頁面:必須提供明確的隱私權與 Cookie 政策說明頁面。
  • 提示訊息機制
    • 僅告知並提供關閉按鈕。
    • 提供「同意」與「關閉」按鈕。
    • 針對 Cookie 類型進行細分(如:允許使用者自訂僅開啟必要性 Cookie)。
  • 狀態管理
    • 關閉提示:僅隱藏橫幅,重新整理後會再次出現。
    • 同意:寫入 Cookie 作為標記 (Flag),後續存取時不再顯示橫幅。

ASP.NET Core 實作技術細節

在 ASP.NET Core 中,可利用內建的 CookiePolicy 中介軟體來處理。

1. 設定 CookiePolicyOptions

Program.cs 中配置中介軟體,設定是否強制要求使用者同意。

csharp
builder.Services.Configure<CookiePolicyOptions>(options => {
    // 若設定為 true,則必須取得使用者同意 (Consent) 才能設定非必要 Cookies
    options.CheckConsentNeeded = context => true;

    options.MinimumSameSitePolicy = SameSiteMode.None;
});

// ...其他程式碼...

app.UseCookiePolicy();

透過 ITrackingConsentFeature 判斷是否需要顯示橫幅。

  • consentFeature?.CanTrack:判斷使用者是否已同意。
  • consentFeature?.CreateConsentCookie():產生同意用的 Cookie 字串。
html
@using Microsoft.AspNetCore.Http.Features

@{
    var consentFeature = Context.Features.Get<ITrackingConsentFeature>();
    var showBanner = !consentFeature?.CanTrack ?? false;
    var cookieString = consentFeature?.CreateConsentCookie();
}

@if (showBanner) {
    <div id="cookieConsent" class="alert alert-info alert-dismissible fade show" role="alert">
        Use this space to summarize your privacy and cookie use policy. <a asp-page="/Privacy">Learn More</a>.
        <button type="button" class="accept-policy close" data-dismiss="alert" aria-label="Close" data-cookie-string="@cookieString">
            <span aria-hidden="true">Accept</span>
        </button>
    </div>
    <script>
        (function () {
            var button = document.querySelector("#cookieConsent button[data-cookie-string]");
            button.addEventListener("click", function (event) {
                document.cookie = button.dataset.cookieString;
            }, false);
        })();
    </script>
}

必要性 Cookies 的處理

什麼情況下會遇到這個問題:當網站有部分功能(如購物車、登入狀態)必須依賴 Cookie 運作,即便使用者未同意追蹤,這些 Cookie 仍需寫入。

對於網站運作不可或缺的 Cookie,應將其標記為 IsEssential = true,這樣即使在 CheckConsentNeededtrue 的情況下,這些 Cookie 仍會被寫入。

csharp
Response.Cookies.Append("name", "value", new CookieOptions {
   IsEssential = true // 表示此 Cookie 是必要的,不受 Consent 限制
});

異動歷程

    • 初版文件建立。